import { createRouter, RouterView, createWebHistory, RouteRecordRaw } from 'vue-router'
import LoginPage from '@/views/login.vue';
import { showMessage, checkAuth } from '@/utils/index'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: '登录',
    component: LoginPage
  },
  {
    path: '/system',
    name: '系统',
    component: () => import('@/components/layout.vue'),
    redirect: '/system/material',
    children: [
      {
        path: 'book',
        name: '图书管理',
        component: () => import('@/views/book.vue')
      },
      {
        path: 'borrow',
        name: '借阅管理',
        component: () => import('@/views/borrow.vue')
      },
      {
        path: 'location',
        name: '位置查询',
        component: () => import('@/views/location.vue')
      },
      {
        path: 'review',
        name: '评论管理',
        component: () => import('@/views/review.vue')
      },
      {
        path: 'management',
        name: '用户管理',
        component: () => import('@/views/management.vue')
      },
    ]
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue')
  },
]


const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const isLoggedIn = sessionStorage.getItem('user_id')
  if (!isLoggedIn && to.name !== '登录') {
    console.log(isLoggedIn);
    showMessage('请先登录', 'error')
    next({ name: '登录' }) // 未登录时跳转到登录页
  } else if (isLoggedIn && to.name === '登录') {
    showMessage('您已登录，请先退出登录', 'error')
    next({ name: '404' }) // 已登录时访问登录页跳转到404页
  } else {
    // 路由鉴权
    if (to.name === '用户管理' && !checkAuth()) {
      showMessage('您没有访问权限', 'error')
      next({ name: '404' })
    } else {
      next()
    }
  }

})

//导出router
export default router



